package com.cn.netty.demo1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;


/**
 * Created by chenyuncong on 2019/9/2.
 */
public class Client {
    public static void main(String[] args) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ByteBuf buf = Unpooled.copiedBuffer("$".getBytes());
                    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf))
                            .addLast(new StringDecoder());
                    ch.pipeline().addLast(new ClientHandler());
                }
            });

            ChannelFuture f = b.connect("193.112.56.81", 9999).sync(); // (5)

            f.channel().writeAndFlush(Unpooled.copiedBuffer("Hello Server$Hello Server$Hello Server".getBytes()));
//            Thread.sleep(1000);
            f.channel().writeAndFlush(Unpooled.copiedBuffer("Hello Server!!".getBytes()));
//            Thread.sleep(1000);
            f.channel().writeAndFlush(Unpooled.copiedBuffer("Hello Server!!!".getBytes()));

            f.channel().closeFuture().sync();
            System.out.println("===========");
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

}
